package com.zzyl.nursing.service.impl;

import com.alibaba.fastjson2.JSON;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住管理Service业务层处理
 *
 * @author zjs
 * @date 2025-05-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住管理
     *
     * @param id 入住管理主键
     * @return 入住管理
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住管理列表
     *
     * @param checkIn 入住管理
     * @return 入住管理
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住管理
     *
     * @param dto 入住管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCheckIn(CheckInApplyDto dto) {
        //入住信息DTO
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        //入住合同DTO
        CheckInContractDto contractDto = dto.getCheckInContractDto();
        //老人家属
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        //老人信息
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();


        //校验老人是否已入住 如果已入住直接抛异常 BaseException
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        //根据老人身份证号和入住状态查询是否有此人
        queryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        queryWrapper.eq(Elder::getStatus, 4);//0=禁用,1=启用,2=请假,3=退住中,4=入住中,5=已退住
        if (elder != null) {
            throw new BaseException("该老人已入住");
        }

        //更新床位的状态
        Long bedId = checkInConfigDto.getBedId();
        Bed bed = bedMapper.selectBedById(bedId);

        bed.setBedStatus(1); //床位状态 : 未入住0, 已入住1, 入驻申请2
        bedMapper.updateById(bed); // MP提供的修改方法

        //新增火更新老人的elder
        elder = saveOrUpdateElder(checkInElderDto, bed);

        //新增合同信息    合同号要求 : HT+16位数字 , 例 : HT20251011012590001
        saveContract(contractDto,elder,checkInConfigDto);

        //新增入住信息    老人家属信息存到remark字段中
        CheckIn checkIn = saveCheckIn(elder,elderFamilyDtoList,checkInConfigDto);

        //新增入住配置
        saveCheckInConfig(checkInConfigDto,checkIn);


        return 1;
    }

    private void saveCheckInConfig(CheckInConfigDto ConfigDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(ConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);//MP新增方法



    }

    //新增入住信息
    private CheckIn saveCheckIn(Elder elder, List<ElderFamilyDto> elderFamilyDtoList, CheckInConfigDto checkInConfigDto) {
        CheckIn checkIn = new CheckIn();

        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());

        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);

        //把集合转成Json字符串
        String string = JSON.toJSONString(elderFamilyDtoList);
        checkIn.setRemark(string);   //老人家属信息存到remark中

        //根据json字符串获取集合
//        List<ElderFamilyDto> elderFamilyDtos = JSON.parseArray(string, ElderFamilyDto.class);
        checkInMapper.insert(checkIn);

        return checkIn;
    }

    //新增合同信息
    private void saveContract(CheckInContractDto ContractDto,Elder elder,CheckInConfigDto checkInConfigDto) {
        //合同号要求     HT20251011012590001
        Contract contract = new Contract();
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());

        contract.setContractName(ContractDto.getContractName());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setAgreementPath(ContractDto.getAgreementPath());
        contract.setThirdPartyPhone(ContractDto.getThirdPartyPhone());
        contract.setThirdPartyName(ContractDto.getThirdPartyName());
        contract.setSignDate(ContractDto.getSignDate());


        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(0);

        contract.setSortOrder(0);

        contractMapper.insert(contract);
    }

    //新增或更新老人elder
    private Elder saveOrUpdateElder(CheckInElderDto elderDto, Bed bed) {
        boolean isNew = false;
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        //根据老人身份证号和入住状态查询是否有此人
        queryWrapper.eq(Elder::getIdCardNo, elderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (elder == null) {
            isNew = true;
            //新增
            elder = new Elder();
        }
        BeanUtils.copyProperties(elderDto, elder); //属性名和类型一致
        elder.setStatus(4); //0=禁用,1=启用,2=请假,3=退住中,4=入住中,5=已退住
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());

        if (isNew) {
            elderMapper.insert(elder);      //MP提供的新增方法 有自动填充的
        } else {
            elderMapper.updateById(elder);  //MP提供的新增方法 有自动填充的
        }
        return elder;
    }

    /**
     * 修改入住管理
     *
     * @param checkIn 入住管理
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住管理
     *
     * @param ids 需要删除的入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住管理信息
     *
     * @param id 入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

}
